package com.mm.base.filter.xss2;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.mm.base.exception.MuMuException;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description 过滤逻辑类-检验请求体的参数
 * @Date 2024/4/11 下午1:59
 * @Author yanglin
 **/
@Component
public class CustomStringDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        String str = jsonParser.getText().trim();
        //sql注入拦截
        if (sqlInject(str)) {
            throw new MuMuException("参数含有非法攻击字符，已禁止继续访问！");
        }
        return xssClean(str);
    }

    /**
     * SQL
     *
     * @param str
     * @return
     */
    public boolean sqlInject(String str) {
        if (StrUtil.isEmpty(str)) {
            return false;
        }
        // 去掉'|"|;|\字符
        str = org.apache.commons.lang3.StringUtils.replace(str, "'", "");
        str = org.apache.commons.lang3.StringUtils.replace(str, "\"", "");
        str = org.apache.commons.lang3.StringUtils.replace(str, ";", "");
        str = org.apache.commons.lang3.StringUtils.replace(str, "\\", "");
        // 转换成小写
        str = str.toLowerCase();
        // 非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "alter", "drop"};
        // 判断是否包含非法字符
        for (String keyword : keywords) {
            if (str.indexOf(keyword) != -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * xss攻击拦截
     *
     * @param value
     * @return
     */
    public String xssClean(String value) {
        if (value == null || "".equals(value)) {
            return value;
        }
        // 非法字符
        String[] keywords = {"<", ">", "<>", "()", ")", "(", "javascript:", "script", "alter", "''", "'"};
        // 判断是否包含非法字符
        for (String keyword : keywords) {
            if (value.indexOf(keyword) != -1) {
                throw new MuMuException("参数含有非法攻击字符，已禁止继续访问！");
            }
        }
        return value;
    }
}
